import { _decorator, Component, EditBox, Label, Node, Slider, Sprite } from 'cc';
import { Soldier } from '../entity/Soldier';
const { ccclass, property } = _decorator;

@ccclass('ArmySoldier')
export class ArmySoldier extends Component {
    @property(Sprite)
    cover:Sprite
    @property(Label)
    soldierName:Label
    @property(Slider)
    slider:Slider
    @property(EditBox)
    editBox:EditBox
    @property(Label)
    count:Label
    @property(Node)
    mask:Node

    private soldierData:Soldier

    /**是否是侦察类型的兵种 */
    get isScout():boolean {
        return this.soldierData.isScout
    }

    start() {
        this.slider.node.on('slide', this.onSlide, this)
        
        this.editBox.node.on('editing-did-ended', this.onEdit, this);
    }

    async setData(soldier:Soldier){
        this.soldierData = soldier

        this.soldierName.string = soldier.name
        this.count.string = soldier.count + ''

        this.editBox.string = '0'
        this.slider.progress = 0

        this.cover.spriteFrame = await soldier.getHeadImg()

    }

    setEnable(flag:boolean){
        if(this.soldierData.count == 0){
            this.mask.active = true
            return
        }

        this.mask.active = !flag
    }

    onSlide(slider: Slider){
        this.editBox.string = Math.floor(this.soldierData.count * slider.progress) + ''
    }
    onEdit(editbox: EditBox){
        let str = editbox.string
        if(!/^\d+$/.test(str)){
            return
        }
        let num = parseInt(str)
        num = num > this.soldierData.count ? this.soldierData.count : num
        this.slider.progress = num / this.soldierData.count
        editbox.string = num + ''
    }

    getArmySoldier(){
        this.soldierData.armyCount = Math.floor(this.soldierData.count * this.slider.progress)
        return this.soldierData
    }
}


